<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class UserInfo extends Model
{
    // 表名,不含前缀
    protected $name = 'user_info';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $type = [
        'createtime' => 'datetime:Y-m-d H:i:s',
        'updatetime' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * @var null|static 实例对象
     */
    protected static $instance = null;

    /**
     * 获取示例
     * @param array $options 实例配置
     * @return static
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) self::$instance = new self($options);

        return self::$instance;
    }

    protected function getCityAttr($value)
    {
        return $value ? explode(',', $value) : [];
    }

    protected function getTopicAttr($value)
    {
        return $value ? explode(',', $value) : [];
    }

    protected function getIndustryAttr($value)
    {
        return $value ? explode(',', $value) : [];
    }

    /**
     * @throws
     * */
    public function submit()
    {
        $model = $this;
        if ($rows = $this->get(['user_id' => $this->data['user_id']])) {
            $model = $rows;
            $this->data['updatetime'] = date('Y-m-d H:i:s');
            // todo 保存修改前后的数据
            $new_date = array_merge($rows->toArray(), $this->data);
            ShowExamine::instance()->allowField(true)->save(['user_id' => $this->data['user_id'], 'type' => 1, 'orign_data' => json_encode($rows, JSON_UNESCAPED_UNICODE), 'new_date' => json_encode($new_date, JSON_UNESCAPED_UNICODE)]);
        }
        $response = $model->allowField(true)->save($this->data);
        if ($response) {
            return true;
        }
        throw new Exception('保存失败');
    }


    /**
     * @param array $params
     * @param int $uid
     * @param int $page
     * @param int $pageSize
     * @return mixed
     * @throws
     * */
    public function getPlatformTeacher(array $params, int $uid, int $page, int $pageSize): array
    {
        $condition['t1.status'] = 1;
        /*$condition['t1.user_id'] = ['<>', $uid];*/
        $whereCondition['t1.status'] = 2;
        $joinSql = '';
        $joinTableSql = '';
        if (!empty($params['channel'])) {
            if ($params['channel'] == 1) { // 公共人脉
                $condition['t2.id'] = null;
                $condition['t3.id'] = null;
                $whereCondition['t2.id'] = null;
                $whereCondition['t3.id'] = null;
            }
            if ($params['channel'] == 2) { // 我的人脉
                $condition['t2.id'] = ['<>', 0];
                $whereCondition['t2.id'] = ['<>', 0];
                $joinSql = ' AND t2.user_id = ' . $uid ?? 0;
                $joinTableSql = ' AND t1.user_id = ' . $uid ?? 0;
            }
            if ($params['channel'] == 3) { // 渠道人脉
                $condition['t3.id'] = ['<>', 0];
                $whereCondition['t3.id'] = ['<>', 0];
            }
        }
        if (!empty($params['address'])) {
            $condition['t1.city'] = ['LIKE', '%' . $params['address'] . '%'];
            $whereCondition['t1.address'] = ['LIKE', '%' . $params['address'] . '%'];
        }
        if (!empty($params['industry'])) {
            $condition['t1.industry'] = ['LIKE', '%' . $params['industry'] . '%'];
            $whereCondition['t1.industry'] = ['LIKE', '%' . $params['industry'] . '%'];
        }
        if (!empty($params['topic'])) {
            $condition['t1.topic'] = ['LIKE', '%' . $params['topic'] . '%'];
            $whereCondition['t1.topic'] = ['LIKE', '%' . $params['topic'] . '%'];
        }
        if (!empty($params['searchName'])) {
            $condition['t1.nickname|t1.name|t1.mobile|t1.wechat_number|t1.introduce|t1.topic|t1.industry|t4.name'] = ['LIKE', '%' . $params['searchName'] . '%'];
            $whereCondition['t1.username|t1.wxh|t1.mobile|t1.introduce|t1.topic|t1.industry|t4.name'] = ['LIKE', '%' . $params['searchName'] . '%'];

        }
        $order = 't1.price desc';
        if (!empty($params['price'])) {
            if ($params['price'] == 'asc') {
                $order = 't1.price asc';
            } else {
                $order = 't1.price desc';
            }
        }
        // todo 用户信息表
        $table1 = $table1_ = $this->alias('t1')
            ->field('t1.id, t1.user_id, t1.nickname, t1.name, t1.city, t1.topic, t1.industry, t1.price, t1.mobile, t1.wechat_number, t1.status, t1.sex')
            ->field('t1.is_rz, t2.id as o_id, t2.state as o_state, t2.user_id as bind_uid, t3.id as m_id')
            ->field('1 as type, 1 as content_type')
            ->join('offline_information t2', 't1.user_id = t2.to_user_id' . $joinSql, 'LEFT')
            ->join('message t3', 't1.user_id = t3.to_user_id', 'LEFT')
            ->join('user_qualifications t4', 't4.user_id = t1.user_id', 'LEFT')
            ->where($condition)
            ->order($order)
            ->group('t1.id')
            ->buildSql();
        // todo 关联表
        $table2 = $table2_ = OfflineInformation::alias('t1')
            ->field('t1.id, t1.to_user_id as user_id, t1.username as nickname, t1.username as name, t1.address as city, t1.topic, t1.industry, t1.price, t1.mobile, t1.wxh as wechat_number')
            ->field('t1.status, t1.sex, IFNULL(t2.is_rz, 1) as is_rz, IFNULL(t2.id, 0) as o_id, t1.state as o_state, t1.user_id as bind_uid, ifNULL(t3.id, 0) as m_id')
            ->field('2 as type, t1.content_type')
            ->join('user_info t2', 't2.user_id = t1.to_user_id AND t2.is_rz = 2' . $joinTableSql, 'LEFT')
            ->join('message t3', 't1.to_user_id = t3.to_user_id', 'LEFT')
            ->join('information_qualifications t4', 't4.oid = t1.id', 'LEFT')
            ->where($whereCondition)
            ->order($order)
            ->group('t1.id')
            ->buildSql();
        $count = count(Db::table($table1 . ' t1')->union($table2, true)->select());
        $list = Db::table($table1 . ' t1')->union($table2, true)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();
        foreach ($list as &$value) {
            $value['is_contact'] = ($value['is_rz'] != 2) ? false : true;
            $value['is_mobile'] = empty($value['mobile']) ? false : true;
            $value['is_wechat'] = empty($value['wechat_number']) ? false : true;
            $value['is_rz'] = ($value['is_rz'] != 2) ? false : true;
            // todo 人脉来源
            $value['source'] = '公共人脉';
            $value['is_rm'] = false;
            $value['is_yq'] = 0;
            if ($message = Message::instance()->where(['user_id' => $uid, 'to_user_id' => $value['user_id'], 'type' => ['in', [1, 2]]])->order('createtime desc')->find()) {
                $value['source'] = '渠道人脉';
                $value['is_yq'] = $message['status'];
                $value['is_rm'] = true;
            }
            if (!empty($value['o_state']) && in_array($value['o_state'], [1, 2]) && ($value['bind_uid'] == $uid)) {
                $value['source'] = '我的人脉';
                $value['is_rm'] = true;
            }
            $value['city'] = empty($value['city']) ? '' : explode(',', $value['city']);
            $value['topic'] = empty($value['topic']) ? '' : explode(',', $value['topic']);
            $value['industry'] = empty($value['industry']) ? '' : explode(',', $value['industry']);
            if (!empty($params['searchName'])) {
                // 使用 preg_replace 高亮关键词
                $value['highlightedName'] = preg_replace(
                    '/(' . preg_quote($params['searchName'], '/') . ')/i',
                    '<span class="highlight">$1</span>',
                    $value['name']
                );
            }

            if (!empty($value['user_id']) && ($value['type'] == 1)) {
                $value['qualifications'] = UserQualifications::instance()->field('id, name, path, path_file_names')->where(['user_id' => $value['user_id'], 'status' => 2])->select();
                $value['content'] = Content::instance()->where(['user_id' => $value['user_id'], 'status' => 2])->select();
            }
            if (($value['type'] == 2)) {
                $value['qualifications'] = InformationQualifications::instance()->field('id, name, path, path_file_names')->where(['oid' => $value['id'], 'status' => 2])->select();
            }
        }
        return array('total' => $count, 'per_page' => $pageSize, 'current_page' => $page, 'last_page' => ceil(($count / $pageSize)), 'data' => $list);
    }

    public function userQualificationsHasMany()
    {
        return $this->hasMany(UserQualifications::class, 'user_id', 'user_id')
            ->where(['status' => 2]);
    }

    public function contentHasMany()
    {
        return $this->hasMany(Content::class, 'user_id', 'user_id')
            ->where(['status' => 2]);
    }

    public function userHasOne()
    {
        return $this->hasOne(User::class, 'id', 'user_id')
            ->bind('avatar');
    }
}